package cn.com.checne.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import cn.com.checne.model.domain.CultureCategory;
import cn.com.checne.model.domain.CultureInfo;
import cn.com.checne.model.domain.LanguageInfo;
import cn.com.checne.model.dto.CultureQuery;
import cn.com.checne.util.TimeUtils;


@Repository
public class CultureInfoDao {
	protected static final Logger log = Logger.getLogger(CultureInfoDao.class);

	/**
	 * create
	 * @param cate
	 * @return
	 */
	public boolean create(CultureInfo culture) {
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String createSql = "insert into tbl_culture(lg_id_fk,culture_cate_id_fk,culture_title,culture_summary,culture_publishdate,culture_publishfrom,culture_author,culture_contenttype,culture_content," +
					"culture_meta_keyword,culture_meta_content,culture_isshowindex,culture_isshowlist,culture_istop,culture_firstimage)" +
					" values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement pstmt = conn.prepareStatement(createSql);
			int i = 0 ;
			pstmt.setInt(++i,culture.getLanguageId());
			pstmt.setInt(++i,culture.getCateId());
			pstmt.setString(++i,culture.getTitle());
			pstmt.setString(++i,culture.getSummary());
			pstmt.setTimestamp(++i, new java.sql.Timestamp(culture.getPublishDate().getTime()));
			pstmt.setString(++i,culture.getPublishFrom());
			pstmt.setString(++i,culture.getAuthor());
			pstmt.setInt(++i,culture.getContentType());
			pstmt.setString(++i,culture.getContent());
			
			pstmt.setString(++i,culture.getMetaKeyword());
			pstmt.setString(++i,culture.getMetaContent());
			
			pstmt.setInt(++i,culture.getIsShowIndex());
			pstmt.setInt(++i,culture.getIsShowList());
			pstmt.setInt(++i,culture.getIsTop());
			
			pstmt.setString(++i,culture.getFirstImage());

			pstmt.execute();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result;
	}

	/**
	 * @param cate
	 * @return
	 */
	public boolean update(CultureInfo culture) {
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_culture set " +
					"lg_id_fk = ?,culture_cate_id_fk = ?,culture_title = ?,culture_summary = ?,culture_publishdate =? ,culture_publishfrom = ?,culture_author =?,culture_contenttype=?,culture_content=?," +
					"culture_meta_keyword =?,culture_meta_content=?,culture_isshowindex=?,culture_isshowlist=?,culture_istop=?,culture_firstimage=? where culture_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			int i = 0 ;
			pstmt.setInt(++i,culture.getLanguageId());
			pstmt.setInt(++i,culture.getCateId());
			pstmt.setString(++i,culture.getTitle());
			pstmt.setString(++i,culture.getSummary());
			pstmt.setTimestamp(++i, new java.sql.Timestamp(culture.getPublishDate().getTime()));
			pstmt.setString(++i,culture.getPublishFrom());
			pstmt.setString(++i,culture.getAuthor());
			pstmt.setInt(++i,culture.getContentType());
			pstmt.setString(++i,culture.getContent());
			
			pstmt.setString(++i,culture.getMetaKeyword());
			pstmt.setString(++i,culture.getMetaContent());
			
			pstmt.setInt(++i,culture.getIsShowIndex());
			pstmt.setInt(++i,culture.getIsShowList());
			pstmt.setInt(++i,culture.getIsTop());
			
			pstmt.setString(++i,culture.getFirstImage());
			
			pstmt.setInt(++i, culture.getCultureId());
			
			pstmt.executeUpdate();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result;
	}

	/**
	 * @param id
	 * @return
	 */
	public boolean delete(int id){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "delete from tbl_culture where culture_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			int i = 0 ;
			pstmt.setInt(++i,id);
			log.info("[SQL]" + pstmt.toString());
			pstmt.executeUpdate();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	/**
	 * 
	 * @param cultureId
	 * @return
	 */
	public CultureInfo getCultureById(int cultureId) {
		CultureInfo culture = new CultureInfo();
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_culture where culture_id = ? ";

			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, cultureId);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			List<CultureInfo> list = getResult(rs);
			culture = (list != null && list.size() > 0 ) ? list.get(0) : culture ;
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return culture;
	}
	/**
	 * 
	 * @param query
	 * @param start
	 * @param num
	 * @return
	 */
	public List<CultureInfo> getCultureListByCondition(CultureQuery query,int start,int num) {
		List<CultureInfo> list = new ArrayList<CultureInfo>();
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_culture where 1=1 " ;
			if(query.getLanguageId() > 0){
				sql += " and lg_id_fk = ? " ;
			}
			if(query.getCateId() > 0){
				sql += " and culture_cate_id_fk = ? " ;
			}
			if(query.getIsShowIndex() > -1){
				sql += " and culture_isshowindex = ? " ;
			}
			if(query.getIsShowList() > -1){
				sql += " and culture_isshowlist = ? " ;
			}
			if(query.getIsTop() > -1){
				sql += " and culture_istop = ? " ;
			}
			if(StringUtils.isNotBlank(query.getKw())){
				sql += " and (culture_title like ? or culture_meta_keyword like ? or culture_meta_content like ? or culture_content like ? )";
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				sql += " and culture_publishdate >= ? ";
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				sql += " and culture_publishdate <= ? ";
			}
			sql += "order by culture_publishdate desc limit ?,?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			if(query.getLanguageId() > 0){
				pstmt.setInt(++i, query.getLanguageId());
			}
			if(query.getCateId() > 0){
				pstmt.setInt(++i, query.getCateId());
			}
			if(query.getIsShowIndex() > -1){
				pstmt.setInt(++i, query.getIsShowIndex());
			}
			if(query.getIsShowList() > -1){
				pstmt.setInt(++i, query.getIsShowList());
			}
			if(query.getIsTop() > -1){
				pstmt.setInt(++i, query.getIsTop());
			}
			if(StringUtils.isNotBlank(query.getKw())){
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getStartTime()).getTime()));
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getEndTime()).getTime()));
			}
			pstmt.setInt(++i, start);
			pstmt.setInt(++i, num);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			list.addAll(getResult(rs));
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 
	 * @param query
	 * @return
	 */
	public int getCultureCountByCondition(CultureQuery query) {
		int total = 0 ;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select count(1) as total from tbl_culture where 1=1 " ;
			if(query.getLanguageId() > 0){
				sql += " and lg_id_fk = ? " ;
			}
			if(query.getCateId() > 0){
				sql += " and culture_cate_id_fk = ? " ;
			}
			if(query.getIsShowIndex() > -1){
				sql += " and culture_isshowindex = ? " ;
			}
			if(query.getIsShowList() > -1){
				sql += " and culture_isshowlist = ? " ;
			}
			if(query.getIsTop() > -1){
				sql += " and culture_istop = ? " ;
			}
			if(StringUtils.isNotBlank(query.getKw())){
				sql += " and (culture_title like ? or culture_meta_keyword like ? or culture_meta_content like ? or culture_content like ? )";
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				sql += " and culture_publishdate >= ? ";
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				sql += " and culture_publishdate <= ? ";
			}
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			if(query.getLanguageId() > 0){
				pstmt.setInt(++i, query.getLanguageId());
			}
			if(query.getCateId() > 0){
				pstmt.setInt(++i, query.getCateId());
			}
			if(query.getIsShowIndex() > -1){
				pstmt.setInt(++i, query.getIsShowIndex());
			}
			if(query.getIsShowList() > -1){
				pstmt.setInt(++i, query.getIsShowList());
			}
			if(query.getIsTop() > -1){
				pstmt.setInt(++i, query.getIsTop());
			}
			if(StringUtils.isNotBlank(query.getKw())){
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getStartTime()).getTime()));
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getEndTime()).getTime()));
			}
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()){
				total = rs.getInt("total");
			}
			rs.close();
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return total;
	}
	
	
	public boolean setShowIndex(int flag,int...cultureIds){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_culture set culture_isshowindex = ? where culture_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			for(int cultureId : cultureIds){
				int i = 0 ;
				pstmt.setInt(++i,flag);
				pstmt.setInt(++i,cultureId);
				pstmt.addBatch();
			}
			pstmt.executeBatch();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	
	public boolean setShowList(int flag,int...cultureIds){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_culture set culture_isshowlist = ? where culture_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			for(int cultureId : cultureIds){
				int i = 0 ;
				pstmt.setInt(++i,flag);
				pstmt.setInt(++i,cultureId);
				pstmt.addBatch();
			}
			pstmt.executeBatch();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	
	public CultureInfo isCultureExist(int languageId ,int cateId){
		CultureInfo culture = null ;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_culture where lg_id_fk = ? and culture_cate_id_fk = ?   " ;
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			pstmt.setInt(++i, languageId);
			pstmt.setInt(++i, cateId);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			List<CultureInfo> list = getResult(rs);
			culture = (list != null && list.size() > 0 ) ? list.get(0) : null;
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return culture ;
	}
	/**
	 * get rseult from resultSet
	 * @param rs
	 * @return
	 */
	public List<CultureInfo> getResult(ResultSet rs) {
		List<CultureInfo> list = new ArrayList<CultureInfo>();
		try {
			CultureInfo culture = null ;
			while(rs.next()) {
				culture = new CultureInfo();
				culture.setCultureId(rs.getInt("culture_id"));
				culture.setTitle(rs.getString("culture_title"));
				culture.setSummary(rs.getString("culture_summary"));
				culture.setPublishDate(rs.getTimestamp("culture_publishdate"));
				culture.setPublishFrom(rs.getString("culture_publishfrom"));
				culture.setAuthor(rs.getString("culture_author"));
				culture.setContentType(rs.getInt("culture_contenttype"));
				culture.setContent(rs.getString("culture_content"));
				culture.setMetaKeyword(rs.getString("culture_meta_keyword"));
				culture.setMetaContent(rs.getString("culture_meta_content"));
				culture.setIsShowIndex(rs.getInt("culture_isshowindex"));
				culture.setIsShowList(rs.getInt("culture_isshowlist"));
				culture.setIsTop(rs.getInt("culture_istop"));
				culture.setFirstImage(rs.getString("culture_firstimage"));
				
				culture.setLanguageId(rs.getInt("lg_id_fk"));
				LanguageInfo lg = new LanguageInfoDao().getLanguageInfoById(culture.getLanguageId());
				culture.setLanguageInfo(lg);
				
				culture.setCateId(rs.getInt("culture_cate_id_fk"));
				CultureCategory cate = new CultureCategoryDao().getCultureCategory(culture.getCateId());
				culture.setCultureCategory(cate);
				
				list.add(culture);
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
}